package cn.tedu.order.tcc;

import cn.tedu.order.entity.Order;
import cn.tedu.order.mapper.OrderMapper;

import io.seata.rm.tcc.api.BusinessActionContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;

/**
 * @author 郭鲁政
 */
@Component
public class OrderTccActionImpl implements OrderTccAction{
    @Autowired
    private OrderMapper orderMapper;
    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public boolean prepare(BusinessActionContext businessActionContext, Long orderId, Long userId, Long productId, Integer count, BigDecimal money) {
        orderMapper.insertFrozen(new Order(orderId,userId,productId,count,money,0));
        ResultHolder.setResult(OrderTccAction.class, businessActionContext.getXid(), "p");
        return true;
    }
    @Transactional(rollbackFor = RuntimeException.class)
    @Override
    public synchronized boolean commit(BusinessActionContext businessActionContext) {
        if (ResultHolder.getResult(OrderTccAction.class, businessActionContext.getXid())==null) {
            return true;
        }
        Long orderId = Long.valueOf(businessActionContext.getActionContext("orderId").toString());
        orderMapper.updateStatusAndCount(orderId,1);
        ResultHolder.removeResult(OrderTccAction.class, businessActionContext.getXid());
        return true;
    }
    @Transactional(rollbackFor = RuntimeException.class)
    @Override
    public synchronized boolean rollback(BusinessActionContext businessActionContext) {
        if (ResultHolder.getResult(OrderTccAction.class, businessActionContext.getXid())==null) {
            return true;
        }
        Long orderId = Long.valueOf(businessActionContext.getActionContext("orderId").toString());
        orderMapper.deleteById(orderId);
        ResultHolder.removeResult(OrderTccAction.class, businessActionContext.getXid());

        return true;
    }
}
